package com.example.filter;

import com.example.bean.User;
import com.example.service.UserService;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginFilter implements Filter{
    private String excludedPaths;

    private String [] excludedPathArray;
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest req =  (HttpServletRequest) arg0;
        if (isFilterExcludeRequest(req)) {
            arg2.doFilter(arg0, arg1);
            return;
        }

        // 是否自动登录
        Cookie autoCookie=null;
        Cookie[] cookies=req.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("autoLogin")) {
                autoCookie=cookie;
            }
        }

        // 如果有自动登录cookie，则自动登录
        if(autoCookie != null) {
            UserService us = new UserService();
            String[] s = autoCookie.getValue().split("@");
            User u = new User();
            u.setUsername(s[0]);
            u.setPassword(s[1]);
            int n = us.selectUserByName(u);
            if(n == 1) {
                u.setId(us.selectUserByUsername(u).getId());
                req.getSession().setAttribute("loginUser", u);
                req.getSession().setMaxInactiveInterval(30*60);
            }
        }

        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        arg2.doFilter(arg0, arg1);    //放行

    }

    // 初始化
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        excludedPaths = arg0.getInitParameter("excludedPaths");
        if(excludedPaths != null){
            excludedPathArray = excludedPaths.split(",");
        }
    }

    // 判断是否需要过滤
    private boolean isFilterExcludeRequest(HttpServletRequest request) {
        if(null != excludedPathArray && excludedPathArray.length > 0) {
            String url = request.getRequestURI();
            for (String ecludedUrl : excludedPathArray) {
                if (ecludedUrl.startsWith("*.")) {
                    // 如果配置的是后缀匹配, 则把前面的*号干掉，然后用endWith来判断
                    if(url.endsWith(ecludedUrl.substring(1))){
                        return true;
                    }
                } else if (ecludedUrl.endsWith("/*")) {
                    if(!ecludedUrl.startsWith("/")) {
                        // 前缀匹配，必须要是/开头
                        ecludedUrl = "/" + ecludedUrl;
                    }
                    // 如果配置是前缀匹配, 则把最后的*号干掉，然后startWith来判断
                    String prffixStr = request.getContextPath() + ecludedUrl.substring(0, ecludedUrl.length() - 1);
                    if(url.startsWith(prffixStr)) {
                        return true;
                    }
                } else {
                    // 如果不是前缀匹配也不是后缀匹配,那就是全路径匹配
                    if(!ecludedUrl.startsWith("/")) {
                        // 全路径匹配，也必须要是/开头
                        ecludedUrl = "/" + ecludedUrl;
                    }
                    String targetUrl = request.getContextPath() + ecludedUrl;
                    if(url.equals(targetUrl)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}